<template>
	<view class="home">
		<view class="top">
			<Tabs :tabs="tabOptions" v-model="tabCurrent" @change="onTabChange" />
		</view>
		
		<view v-show="tabCurrent === 0">
			<map
				class="map-comp"
				id="map"
				show-location
				:scale="10"
				:markers="markerStore.markers"
				:latitude="locationStore.latitude"
				:longitude="locationStore.longitude"
				:polyline="polyline"
				@markertap="onTapMarker"
				@regionchange="onRegionChange"
			></map>
			<view
				v-show="checkedMarkerId > 0"
				:class="['checked-marker', checkedDevice.causedBy === 'exception' && 'exception', checkedDevice.causedBy === 'warning' && 'warning']"
			>
				<template v-if="checkedDevice.causedBy === 'warning'">
					<view class="marker-title flex-row">
						患者状况：{{ ['疑似心脏骤停', '非疑似心脏骤停'][checkedDevice.patient_condition] || '-' }}
						<text class="iconfont icon-close" @click.stop="checkedMarkerId = 0"></text>
					</view>
					<view class="address">
						<view class="text">{{ checkedDevice.region }}{{ checkedDevice.address }}</view>
						<image class="nav-icon" src="/static/nav.png" @click.stop="tapNavMap" />
					</view>
					<button class="btn-primary btn-nav" @click.stop="tapNavMap">立即前往</button>
				</template>
				<template v-else>
					<view class="marker-title flex-row">
						设备序列号：{{ checkedDevice.host_serial_no || '-' }}
						<text class="iconfont icon-close" @click.stop="checkedMarkerId = 0"></text>
					</view>
					<Equipment :equipment-detail="checkedDevice" @check="toDetail(checkedDevice)" />
				</template>
			</view>
			<view class="location" @click.stop="moveToLocation">
				<image class="location-icon" src="/static/map/location.png" />
			</view>
			<button class="btn-primary btn-alarm" @click.stop="showPopup = true">一键呼救</button>
		</view>
		<view v-show="tabCurrent === 1" class="list">
			<template v-if="list.length">
				<Equipment v-for="i of list" :key="i.id" :equipment-detail="i" @check="toDetail(i)" />
			</template>
			<view v-else class="no-data">暂无数据</view>
		</view>
		<FillinPatientInfo v-model="showPopup" @confirm="onConfirmFillinPatientInfo" />
	</view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onReady, onReachBottom } from '@dcloudio/uni-app';
import { useLocationStore } from '@/store/location';
import { useMarkerStore } from '@/store/marker';
import { tabOptions } from './useTabs';
import { useList } from '@/hooks/useList';
import { fetchDeviceList, postAlarms } from '@/api/home';
import { postNav } from '@/api';
import Tabs from '@/components/Tabs/index.vue';
import Equipment from '@/components/Equipment/index.vue';
import FillinPatientInfo from './components/FillinPatientInfo.vue';

const polyline = ref([])
const locationStore = useLocationStore();
const markerStore = useMarkerStore();
const tabCurrent = ref(0);
const query = ref({
	user_lng: 0,
	user_lat: 0,
	choose_lng: 0,
	choose_lat: 0,
	map_level: 10
});
/**选中的标点 默认0未选择 */
const checkedMarkerId = ref(0);
/**移动后的坐标中心点 */
let offsetLatitude = 0;
/**移动后的坐标中心点 */
let offsetLongitude = 0;
const checkedDevice = ref({});
const showPopup = ref(false);
const { list, getFirstList, getMoreList } = useList(fetchDeviceList, query);
let mapContext = '';
onReady(() => {
	mapContext = uni.createMapContext('map');
	locationStore.getLocation().then(() => {
		getMapScale().then((res) => {
			offsetLatitude = locationStore.latitude;
			offsetLongitude = locationStore.longitude;
			query.value = {
				user_lng: locationStore.longitude,
				user_lat: locationStore.latitude,
				choose_lng: offsetLongitude,
				choose_lat: offsetLatitude,
				map_level: res
			};
			markerStore.getMarkers(query.value);
		});
	});
});

onReachBottom(getMoreList);

watch(checkedMarkerId, (newId, oldId) => {
	const checkedMarker = markerStore.markers.find((i) => i.id === newId);
	const normalMarker = markerStore.markers.find((i) => i.id === oldId);
	if (normalMarker) {
		normalMarker.iconPath = `/static/marker/${normalMarker.causedBy}.png`;
		normalMarker.height = 32;
	}
	if (checkedMarker) {
		checkedMarker.iconPath = `/static/marker/${checkedMarker.causedBy}-checked.png`;
		checkedMarker.height = 46;
		checkedDevice.value = checkedMarker;
	}
});

function onConfirmFillinPatientInfo(patientInfo) {
	const showMsg = (title) => uni.showToast({ title, icon: 'none' });
	const params = {
		patient_condition: patientInfo.patientStatus + 1,
		region: patientInfo.address,
		address: patientInfo.fullAddress,
		longitude: patientInfo.longitude,
		latitude: patientInfo.latitude,
		addr:patientInfo.addr
	};
	uni.showLoading();
	postAlarms(params)
		.then(() => {
			showMsg('提交成功');
		})
		.finally(uni.hideLoading);
}

const toDetail = (i) => {
	uni.navigateTo({
		url: '/pages/equipmentDetails/index?serialNum=' + i.host_serial_no
	});
};

function tapNavMap() {
	postNav({
		latitude: +checkedDevice.value.latitude,
		longitude: +checkedDevice.value.longitude,
		region: checkedDevice.value.region,
		address: checkedDevice.value.address,
		host_serial_no: checkedDevice.value.host_serial_no
	});
	uni.openLocation({
		address: checkedDevice.value.region + checkedDevice.value.address,
		latitude: +checkedDevice.value.latitude,
		longitude: +checkedDevice.value.longitude
	});
}

function onTapMarker(e) {
	const { markerId } = e.detail;
	checkedMarkerId.value = markerId !== checkedMarkerId.value ? markerId : 0;
}

function onRegionChange(e) {
	if (!mapContext) return;
	console.log(e);
	if (e.detail.type === 'end') {
		const { latitude, longitude } = e.detail.centerLocation;
		offsetLatitude = latitude;
		offsetLongitude = longitude;
		getMapScale().then((res) => {
			query.value = {
				user_lng: locationStore.longitude,
				user_lat: locationStore.latitude,
				choose_lng: offsetLongitude,
				choose_lat: offsetLatitude,
				map_level: res
			};
			markerStore.getMarkers(query.value);
		});
	}
}

function moveToLocation() {
	// const mapContext = uni.createMapContext('map')
	mapContext.moveToLocation();
	offsetLatitude = locationStore.latitude;
	offsetLongitude = locationStore.longitude;
}

function getMapScale() {
	return new Promise((resolve, reject) => {
		if (!mapContext) reject(false);
		// const mapContext = uni.createMapContext('map')
		mapContext.getScale({
			success(res) {
				resolve(Math.round(res.scale));
			},
			fail() {
				reject(false);
			}
		});
	});
}

/**
 * 监听tab改变
 */
function onTabChange() {
	if (tabCurrent.value === 1) {
		getMapScale().then((res) => {
			query.value = {
				user_lng: locationStore.longitude,
				user_lat: locationStore.latitude,
				choose_lng: offsetLongitude,
				choose_lat: offsetLatitude,
				map_level: res
			};
			getFirstList();
		});
	} else {
		getMapScale().then((res) => {
			query.value = {
				user_lng: locationStore.longitude,
				user_lat: locationStore.latitude,
				choose_lng: offsetLongitude,
				choose_lat: offsetLatitude,
				map_level: res
			};
			markerStore.getMarkers(query.value);
		});
	}
}
</script>

<style scoped lang="scss">
.home {
	min-height: 100vh;
	background-color: #f8f8f8;
	.map-comp {
		width: 100%;
		height: calc(100vh - 88rpx);
	}
	.checked-marker {
		--bg-color: rgba(128, 221, 154, 0.4);
		position: fixed;
		top: 148rpx;
		left: 30rpx;
		right: 30rpx;
		border-radius: 16rpx;
		background-color: #fff;
		background-image: linear-gradient(var(--bg-color), rgba(255, 255, 255, 0.68) 30%, #fff);
		&.exception {
			--bg-color: rgba(254, 174, 9, 0.4);
		}
		&.warning {
			--bg-color: rgba(232, 89, 74, 0.4);
		}
		.marker-title {
			height: 90rpx;
			color: #333;
			font-weight: bold;
			padding-left: 30rpx;
			padding-right: 30rpx;
			.icon-close {
				font-size: 20rpx;
				padding: 6rpx;
				border-radius: 50%;
				border: 2rpx solid #333;
			}
		}
		:deep(.equipment) {
			margin: 0;
		}
		.address {
			color: #999;
			font-size: 26rpx;
			align-items: center;
			display: flex;
			padding: 30rpx;
			column-gap: 20rpx;
			.text {
				@include ellipsis(2);
			}
			.nav-icon {
				width: 48rpx;
				height: 48rpx;
				flex-shrink: 0;
			}
		}
		.btn-nav {
			margin: 0 30rpx 40rpx;
		}
	}
	.location {
		width: 84rpx;
		height: 84rpx;
		border-radius: 20rpx;
		background-color: #ffffff;
		box-shadow: 0rpx 1rpx 7rpx 0rpx rgba(3, 0, 0, 0.35);
		position: fixed;
		bottom: 270rpx;
		right: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		.location-icon {
			width: 60rpx;
			height: 60rpx;
		}
	}
	.btn-alarm {
		background-color: $red-color;
		position: fixed;
		bottom: 30rpx;
		right: 50rpx;
		left: 50rpx;
	}
	.list {
		overflow: hidden;
	}
}
.top {
	position: sticky;
	top: 0;
}
</style>
